import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:audio_session/audio_session.dart';
import 'package:common_utils/common_utils.dart';
import 'package:fate_blind_box/chat_view/chat_net_image.dart';
import 'package:fate_blind_box/chat_view/image_message_view.dart';
import 'package:fate_blind_box/chat_view/video_message_data.dart';
import 'package:fate_blind_box/im/person_info.dart';
import 'package:fate_blind_box/routes/page_route_names.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/ui/Home/activity/act_list_model.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:just_audio/just_audio.dart';
import 'package:permission_handler/permission_handler.dart';
import '../network/Api.dart';
import '../ui/Home/activity/act_details_page.dart';
import 'package:date_format/date_format.dart';
import '../widget/photo_view.dart';
import 'entity/chat_group_entity.dart';

enum RecordPlayState {
  record,
  recording,
  play,
  playing,
}

class MessageContent extends StatefulWidget {
  List<EMMessage> mesList;
  int index;

  String username;

  List avatarList;

  MessageContent(this.mesList, this.index, this.username, this.avatarList,
      {Key? key})
      : super(key: key);

  @override
  State<MessageContent> createState() => _MessageContentState();
}

class _MessageContentState extends State<MessageContent> {
  late EMMessage msg;
  late EMTextMessageBody textBody;
  late EMMessageBody body;
  late EMVoiceMessageBody voiceBody;
  late EMImageMessageBody imageBody;
  late EMVideoMessageBody videoBody;
  late EMCustomMessageBody shareUrlBody;
  Map _userInfo = {};
  String content = "";
  Map<String, dynamic> jsonContent = {};
  String voiceTime = '';

  String _playerTxt = "";

  RecordPlayState _state = RecordPlayState.play;
  FlutterSoundPlayer playerModule = FlutterSoundPlayer();
  late StreamSubscription _recorderSubscription;
  late StreamSubscription _playerSubscription;
  final player = AudioPlayer();

  final double minWidth = 90;
  final double maxWidths = 250;
  final double maxDuration = 60;
  FuturePopular dataModel = FuturePopular();
  String showTime = '';

  ChatGroupEntity? model;

  @override
  void initState() {
    super.initState();
    setState(() {
      msg = widget.mesList[widget.index];
      if (msg != null) {
        showTime = DateUtil.formatDate(
            DateTime.fromMillisecondsSinceEpoch(
              msg.localTime,
            ),
            format: 'MM月dd日 HH:mm');
      }
      body = msg.body;
      if (kDebugMode) {
        // print('----------------ddd-' +
        //     msg.toString() +
        //     msg.serverTime.toString());
        Provider.cache("serverTime", msg.serverTime.toString());
      }
      if (msg.body.type == MessageType.TXT) {
        //文字
        textBody = body as EMTextMessageBody;
        content = textBody.content;
      }
      if (msg.body.type == MessageType.VOICE) {
        //音频
        voiceBody = body as EMVoiceMessageBody;
        if(voiceBody.remotePath==null){
          content = voiceBody.localPath;
        }else{
          content = voiceBody.remotePath!;
        }
        voiceTime = voiceBody.duration.toString();
        voiceTime == '0' ? voiceTime = '1' : voiceTime;
      }
      if (msg.body.type == MessageType.IMAGE) {
        //图片
        // print('xxx  $imageBody');
        imageBody = body as EMImageMessageBody;
        print(
            '消息显示:${imageBody.localPath}\n--缩略图的本地路径:${imageBody.thumbnailLocalPath}\n----缩略图的服务器路径:${imageBody.thumbnailRemotePath}---${imageBody.thumbnailStatus}');
        if(imageBody.remotePath!=null){
          content = imageBody.remotePath!;
        }else{
          content = imageBody.localPath;
        }

      }
      if (msg.body.type == MessageType.VIDEO) {
        print('收到视频消息:${msg}');
        //视频
        videoBody = body as EMVideoMessageBody;
        if(videoBody.remotePath!=null){
          content = videoBody.remotePath!;
        }else{
          content = videoBody.localPath;
        }
      }
      if (msg.body.type == MessageType.CUSTOM) {
        Map json = msg.body.toJson();
        if (json['event'] != null && json['event'] == 'addGroup') {
          model = ChatGroupEntity.fromJson(json);
        } else {
          shareUrlBody = body as EMCustomMessageBody;
          content = shareUrlBody.params?['content'] ?? '';
          if (content.isNotEmpty) {
            jsonContent = jsonDecode(content);
            dataModel = FuturePopular.fromJson(jsonContent);
          }
        }
      }
      _getMemberInfo(msg.from.toString());
    });

    if (kDebugMode) {
      print('rx---from------' + msg.from.toString());
      print('rx---to------' + msg.to.toString());
      print('rx---name------' + widget.username);
      print('rx---direction------' + msg.direction.toString());
      print('rx---body------' + msg.body.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    if (msg.body.type == MessageType.CUSTOM && model?.event == 'addGroup') {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            showTime,
            style: TextStyle(fontSize: 10, color: ThemeColor.textColorSecond),
          ),
          SizedBox(height: 2.w),
          Text.rich(
            TextSpan(text: '欢迎 ', children: [
              TextSpan(
                text: '${model?.params?.userName}',
                style: TextStyle(fontSize: 12.sp, color: Colors.blue),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    Get.to(PersonInfo(sig: model?.params?.id));
                  },
              ),
              TextSpan(
                  text: ' 加入群聊',
                  style: TextStyle(
                      fontSize: 12.sp, color: ThemeColor.textColorSecond)),
            ]),
            style:
                TextStyle(fontSize: 12.sp, color: ThemeColor.textColorSecond),
          ),
        ],
      );
    } else {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Center(
              child: Text(
            showTime,
            style: TextStyle(fontSize: 10, color: ThemeColor.textColorSecond),
          )),
          const SizedBox(
            height: 2,
          ),
          contentView(),
        ],
      );
    }
  }

  /// 消息体
  Widget contentView() {
    return Row(
      textDirection: msg.direction == MessageDirection.SEND
          ? TextDirection.rtl
          : TextDirection.ltr,
      children: [
        headerView(),
        getMessageType(msg.body.type),
      ],
    );
  }

  /// 消息header
  Widget headerView() {
    return InkWell(
      onTap: () {
        if (_userInfo['id'].toString().isEmpty) return;
        AppWidget.setStatusBlackView();
        Get.to(PersonInfo(sig: _userInfo['id'].toString()),
            routeName: PageRouteNames.personInfoPage);
      },
      child: Container(
          margin: EdgeInsets.only(left: 5.w, top: 10.w, bottom: 10.w, right: 5.w),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(5.w),
            child: msg.direction == MessageDirection.SEND ||
                    msg.direction == MessageDirection.RECEIVE
                ? ChatNetImage(
                    imageUrl: Provider.fixAvatar(_userInfo['profilePhoto']),
                    width: 40.w,
                    height: 40.w,
                  )
                : ChatNetImage(
                    imageUrl: Provider.fixAvatar(Provider.profilePhoto),
                    width: 40.w,
                    height: 40.w,
                  ),
          )),
    );
  }

  Widget getMessageType(MessageType type) {
    bool isNotSelf = msg.direction == MessageDirection.RECEIVE;
    Color bgColor = isNotSelf ? Colors.white : ThemeColor.appColor;
    Color textColor = isNotSelf ? Colors.black : Colors.white;
    switch (type) {
      case MessageType.TXT:
        return Container(
          padding: const EdgeInsets.all(10),
          margin: const EdgeInsets.only(top: 10, bottom: 10),
          constraints: const BoxConstraints(maxWidth: 240),
          //height: 40,
          decoration: BoxDecoration(
              color: bgColor, borderRadius: BorderRadius.circular(3.0)),
          child: Text(
            content,
            style: TextStyle(
              color: textColor,
              fontSize: 14,
            ),
          ),
        );
        break;
      case MessageType.VOICE:
        return LayoutBuilder(builder: (context, constraints) {
          final maxWidth = min(constraints.maxWidth, maxWidths);
          final width = minWidth +
              (maxWidth - minWidth) *
                  (voiceBody.duration.toDouble() / maxDuration);
          return GestureDetector(
              onTap: () async {
                player.setUrl(content);
                final session = await AudioSession.instance;
                session.configure(const AudioSessionConfiguration.music());
                player.play();
                // _startPlayer(content);
                if (kDebugMode) {
                  print('----------------' + content);
                }
                // if (_state == RecordPlayState.play) {
                //   if(content.isEmpty)return;
                //   _startPlayer(content);
                // } else if (_state == RecordPlayState.playing) {
                //   _pauseResumePlayer();
                // }
              },
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 250),
                width: width,
                height: 40,
                padding: const EdgeInsets.all(10),
                margin: const EdgeInsets.only(top: 10, bottom: 10),
                constraints: const BoxConstraints(maxWidth: 240),
                decoration: BoxDecoration(
                    color: bgColor, borderRadius: BorderRadius.circular(3.0)),
                child: isNotSelf
                    ? Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Image.asset(
                            'images/left_voice_3.png',
                            width: 25,
                            height: 25,
                            alignment: Alignment.centerLeft,
                            color: textColor,
                          ),
                          const SizedBox(
                            width: 8,
                          ),
                          Text(
                            "$voiceTime''",
                            style: TextStyle(color: textColor),
                          ),
                        ],
                      )
                    : Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Text(
                            "$voiceTime''",
                            style: TextStyle(color: textColor),
                          ),
                          const SizedBox(
                            width: 8,
                          ),
                          Image.asset(
                            'images/right_voice.png',
                            width: 25,
                            height: 25,
                            alignment: Alignment.centerRight,
                            color: textColor,
                          )
                        ],
                      ),
              ));
        });
      case MessageType.IMAGE:
        return ImageMessageView(messageBody: imageBody,message: msg,);
      case MessageType.VIDEO:
        return VideoMessageData(videoMessage: videoBody,message: msg,);
      case MessageType.CUSTOM:
        {
          String actiCover = dataModel.actiCover ?? '';
          String title = dataModel.actiTitle ?? '';
          String startTime = dataModel.actiTime ?? '';
          String address = dataModel.actiAddr ?? '';
          String actiCost = dataModel.actiCost ?? '';
          return Container(
            padding: EdgeInsets.only(left: 16, right: 13, top: 13, bottom: 12),
            margin: const EdgeInsets.only(top: 10, bottom: 10),
            constraints: BoxConstraints(maxWidth: 1.sw - 69 - 62 - 20),
            alignment: isNotSelf ? Alignment.centerLeft : Alignment.centerRight,
            decoration: BoxDecoration(
                color: Provider.userEaseName.isNotEmpty &&
                        msg.from != Provider.userEaseName
                    ? const Color(0xffffffff)
                    : const Color(0xff98e165),
                borderRadius: BorderRadius.circular(3.0)),
            child: Provider.userEaseName.isNotEmpty &&
                    msg.from != Provider.userEaseName
                ? getCoverImgView(
                    actiCover: actiCover,
                    title: title,
                    address: address,
                    startTime: startTime,
                    actiCost: actiCost,
                    crossAxis: CrossAxisAlignment.end,
                    mainAxis: MainAxisAlignment.end)
                : getCoverImgView(
                    actiCover: actiCover,
                    title: title,
                    address: address,
                    startTime: startTime,
                    actiCost: actiCost,
                    crossAxis: CrossAxisAlignment.start,
                    mainAxis: MainAxisAlignment.start),
          );
        }
    }
    return Container();
  }

  Widget getCoverImgView(
      {String actiCover = '',
      String title = '',
      String startTime = '',
      String endTime = '',
      String address = '',
      String actiCost = '',
      CrossAxisAlignment crossAxis = CrossAxisAlignment.start,
      MainAxisAlignment mainAxis = MainAxisAlignment.start}) {
    return GestureDetector(
      onTap: () {
        Get.to(ActDetailsPage(
          dataModel: dataModel,
          actId: dataModel.activityId,
        ));
      },
      child: Column(
        crossAxisAlignment: crossAxis,
        children: [
          ClipRRect(
              borderRadius: BorderRadius.circular(5),
              child: getCoverImg(actiCover)),
          const SizedBox(
            height: 14,
          ),
          Text(
            title,
            style: TextStyle(fontSize: 14, color: ThemeColor.black2C2C2CColor),
          ),
          const SizedBox(
            height: 7,
          ),
          Row(
            children: [
              Image.asset(
                'images/scan/deails_money_type.png',
                width: 14,
              ),
              const SizedBox(
                width: 2,
              ),
              Text(
                actiCost,
                style:
                    TextStyle(color: ThemeColor.redE84D46Color, fontSize: 14),
              ),
            ],
          ),
          const SizedBox(
            height: 7,
          ),
          Row(
            children: [
              Image.asset(
                'images/scan/details_time_clock.png',
                width: 14,
              ),
              const SizedBox(
                width: 2,
              ),
              Text(
                startTime,
                style:
                    TextStyle(color: ThemeColor.gray99A3B4Color, fontSize: 14),
              )
            ],
          ),
          const SizedBox(
            height: 7,
          ),
          Row(
            children: [
              Image.asset(
                'images/scan/details_map_location.png',
                width: 14,
              ),
              const SizedBox(
                width: 2,
              ),
              Text(
                address,
                style:
                    TextStyle(color: ThemeColor.gray99A3B4Color, fontSize: 14),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget getCoverImg(String actiCover) {
    double imgWidth = 195;
    double imgHeight = 112;
    return actiCover.isNotEmpty
        ? ChatNetImage(
            imageUrl: actiCover,
            width: imgWidth,
            height: imgHeight,
          )
        : Image.asset(
            'images/map/oryj_logo_big.png',
            width: imgWidth,
            height: imgHeight,
          );
  }

  /// 判断文件是否存在
  Future _fileExists(String path) async {
    return await File(path).exists();
  }

  /// 开始播放
  Future<void> _startPlayer(String path) async {
    var status = await getPermissionStatus();
    try {
      print('vvv $path  ${_fileExists(path)}');
      if (await _fileExists(path)) {
        await playerModule.startPlayer(
            fromURI: path,
            codec: Codec.pcm16WAV,
            whenFinished: () {
              print('==> 结束播放');
              _stopPlayer();
              setState(() {});
            });
      } else {
        EasyLoading.showToast("未找到文件路径");
        throw RecordingPermissionException("未找到文件路径");
      }

      _cancelPlayerSubscriptions();
      _playerSubscription = playerModule.onProgress?.listen((e) {
        if (e != null) {
          if (kDebugMode) {
            print(
                "${e.duration} -- ${e.position} -- ${e.duration.inMilliseconds} -- ${e.position.inMilliseconds}");
          }
          DateTime date = DateTime.fromMillisecondsSinceEpoch(
              e.position.inMilliseconds,
              isUtc: true);
          String txt =
              DateTime.fromMillisecondsSinceEpoch(date.millisecondsSinceEpoch)
                  as String;

          setState(() {
            _playerTxt = txt.substring(0, 8);
          });
        }
      }) as StreamSubscription;
      setState(() {
        _state = RecordPlayState.playing;
      });
      if (kDebugMode) {
        print('===> 开始播放');
      }
    } catch (err) {
      if (kDebugMode) {
        print('==> 错误: $err');
      }
    }
    setState(() {});
  }

  //动态获取权限
  Future<bool> getPermissionStatus() async {
    Permission permission = Permission.microphone;
    //granted 通过，denied 被拒绝，permanentlyDenied 拒绝且不在提示
    PermissionStatus status = await permission.status;
    if (status.isGranted) {
      return true;
    } else if (status.isDenied) {
      requestPermission(permission);
    } else if (status.isPermanentlyDenied) {
      openAppSettings();
    } else if (status.isRestricted) {
      requestPermission(permission);
    } else {}
    return false;
  }

  ///申请权限
  void requestPermission(Permission permission) async {
    PermissionStatus status = await permission.request();
    if (status.isPermanentlyDenied) {
      openAppSettings();
    }
  }

  /// 结束播放
  Future<void> _stopPlayer() async {
    try {
      await playerModule.stopPlayer();
      if (kDebugMode) {
        print('===> 结束播放');
      }
      _cancelPlayerSubscriptions();
    } catch (err) {
      if (kDebugMode) {
        print('==> 错误: $err');
      }
    }
    setState(() {
      _state = RecordPlayState.play;
    });
  }

  /// 取消录音监听
  void _cancelRecorderSubscriptions() {
    _recorderSubscription.cancel();
  }

  /// 取消播放监听
  void _cancelPlayerSubscriptions() {
    _playerSubscription.cancel();
  }

  _getMemberInfo(String from) async {
    final res = await Api.getInstance().getUserInfo(from);
    if (res['code'] == 0) {
      final data = res['data'];
      if (data != null) {
        if (mounted) {
          setState(() {
            _userInfo = data;
            if (kDebugMode) {
              print('----!----------' + _userInfo.toString());
            }
          });
        }
      } else {
        // ThemeSnackBar.show(context, "用户信息错误");
      }
    } else {
      // ThemeSnackBar.show(context, res['msg']);
    }
  }
}
